import Vue from "vue";

//导入vuex-store状态管理
import Vuex from "vuex";
Vue.use(Vuex);

let car = window.JSON.parse(localStorage.getItem("cart") || "[]");

const store = new Vuex.Store({
  state: {
    //购物车里面每个商品对应一个对象{id, count}
    cart: car,
  },
  mutations: {
    //将商品丢到cart
    addToCart(state, goods) {
      //如果已经有这个商品 只用直接更新数量 如果没有 才push加入新的
      let flag = false;
      state.cart.some((item, i) => {
        if (item.id == goods.id) {
          item.count += goods.count;
          flag = true;
          return true;
        }
      });
      //没找到
      if (!flag) state.cart.push(goods);

      //放到localstorage里
      localStorage.setItem("cart", window.JSON.stringify(state.cart));
    },
    updateGoodsCount(state, goods) {
      state.cart.some((item) => {
        if (item.id == goods.id) {
          item.count = goods.count;
          return true;
        }
      });
      localStorage.setItem("cart", window.JSON.stringify(state.cart));
    },
    delfromcart(state, id) {
      state.cart.some((item, i) => {
        if (item.id == id) {
          state.cart.splice(i, 1);
          return true;
        }
      });
      localStorage.setItem("cart", window.JSON.stringify(state.cart));
    },
  },

  getters: {
    //计算购物车所有count
    totalcount(state) {
      let c = 0;
      state.cart.forEach((item) => (c += item.count));
      return c;
    },
    idStr(state) {
      let arr = [];
      state.cart.forEach((item) => arr.push(item.id));
      return arr.join(",");
    },
    countObj(state) {
      /* 获取 购物车中 商品的Id和商品数量的键值对对应关系 */
      let o = {};
      state.cart.forEach((item) => (o[item.id] = item.count));
      return o;
      /* {
        88: 3,
        89: 5
      } */
    },
    selectcount(state) {
      let c = 0;
      state.cart.forEach((item) => (c += item.count));
      return c;
    },
    amount(state) {
      /* 总价 */
      let c = 0;
      state.cart.forEach((item) => {
        // 只有这一项商品被选中了，才把数量加起来
        c += item.count * item.price;
      });
      return c;
    },
  },
});

export default store;
